package com.scalar.chiptrack.operations.dataentry.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.utils.AutoGrowingArrayList;
import com.scalar.chiptrack.operations.discrepancyLotsNotifications.DiscrepancyLot;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.dataentry.forms.DataEntryLotsForm;
import com.scalar.chiptrack.operations.dataentry.DataEntryLot;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 24 Aug, 2009
 * Time: 12:36:37 PM
 * To change this template use File | Settings | File Templates.
 */
public class DataEntryLotsAction extends ChipTrackAction
{
    private final String ACTION_NAME = "/dataEntryLots.do" ;

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
		String action = request.getParameter( "action" );
        DataEntryLotsForm dataEntryLotsForm = (DataEntryLotsForm) form;
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        ArrayList<DataEntryLot> closeDatEntryLotList = new ArrayList<DataEntryLot>();
        HashMap<String, String> errors  = new HashMap<String, String>();
        HashMap<String, String> info    = new HashMap<String, String>();
        
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME + "?" + request.getQueryString() );
            return ( mapping.findForward ( "login" ) );
        }

        if ( action == null || action.trim().length() == 0 )
        {
            dataEntryLotsForm.setPsType("0");
            dataEntryLotsForm.setVendorName("0");
            action = "searchScreen";
        }
        String forward = "success";
        if ( "searchScreen".equalsIgnoreCase( action ) )
        {               
            forward = "success";
        }
        else if ( "search".equalsIgnoreCase( action ) )
        {
            try
            {
                AutoGrowingArrayList dataEntryLotsList = DataEntryDAO.getDataEntryLots(null, dataEntryLotsForm.getPsType(), dataEntryLotsForm.getVendorName() );
                dataEntryLotsForm.setDataEntryLots( dataEntryLotsList );
                request.setAttribute( "showDataEntryLots", "true" );
            }
            catch ( Exception e )
            {   e.printStackTrace();
                errors.put ( "Could not load DataEntry Lots", null );
            }
            forward = "success";
        }
        else if ( "save".equalsIgnoreCase( action ) )
        {
            forward = "save";
            DataEntryLot dataEntryLot = null;
            if ( dataEntryLotsForm.getDataEntryLots() != null && dataEntryLotsForm.getDataEntryLots().size() >0 )
            {
                for( int i=0; i < dataEntryLotsForm.getDataEntryLots().size(); i++)
                {
                    dataEntryLot = (DataEntryLot)dataEntryLotsForm.getDataEntryLots().get(i);

                    if ( dataEntryLot.isSelected() )
                    {
                        closeDatEntryLotList.add( dataEntryLot );
                    }
                }
            }

            dataEntryLotsForm.setConfirmDataEntryLots( closeDatEntryLotList );

            saveToken( request );
        }
        else if ( "confirm".equalsIgnoreCase( action ) )
        {

            DBTransaction dbTransaction = null;
            boolean success = false;
            try
            {
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
                if ( isTokenValid( request ) )
                {
                    DataEntryDAO.closeDataEntryLots( dbTransaction, dataEntryLotsForm.getConfirmDataEntryLots(), user );
                    if ( dbTransaction != null )
                    {
                        dbTransaction.commit();
                        info.put( "Selected DataEntry Lots Closed successfully", null );
                    }
                    success = true;
                }
                else
                {
                    errors.put("Invalid Request" , null );
                }
            }
            catch ( ScalarException e )
            {
                e.printStackTrace();
                errors.put ( "Could not close selected DataEntry Lots", null );
            }
            finally
            {
                if ( dbTransaction != null )
                {
                    if ( !success )
                    {
                        dbTransaction.rollback();
                    }
                    dbTransaction = null;
                }
            }
            dataEntryLotsForm.setPsType("0");
            dataEntryLotsForm.setVendorName("0");
            forward = "success";
        }

        request.setAttribute( "psTypes", NewProductDAO.loadAllProcessesFromDB( null, true ) );

        if ( dataEntryLotsForm.getPsType() != null && dataEntryLotsForm.getPsType().trim().length() > 0
                && !"0".equalsIgnoreCase( dataEntryLotsForm.getPsType().trim() )  )
        {
            request.setAttribute( "vendors", VendorDAO.getVendorNamesByProcessByUserType( null, dataEntryLotsForm.getPsType(), user) );
        }
        else
        {
            request.setAttribute( "vendors", VendorDAO.getVendorNamesByProcessByUserType( null, "All", user) );
        }


        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
        return mapping.findForward(forward);
    }
}
